﻿using AutoMapper;
using DTO;
using DTO.DTO.Com.BasicType;
using IServices.Com;
using Microsoft.AspNetCore.Mvc;
using Web.Controllers;
using Web.Filter;
using Web.Framework;

namespace Web.Areas.Basic.Controllers
{
    public class BasicTypeController : BaseController
    {
        private readonly IBasicTypeService _service;
        private readonly IUserRole _userRole;
        public BasicTypeController(IHttpContextAccessor httpContextAccessor, IMapper mapper, IBasicTypeService service, IUserRole userRole) 
            : base(httpContextAccessor, mapper)
        {
            _service = service;
            _userRole = userRole;
        }
        // GET: Bus/BasicType
        public IActionResult Index(string type, string parentId)
        {
            var pageUrl = $"/Basic/BasicType/Index?type={type}";
            var result = _userRole.Check(UserInfo, pageUrl);
            if (!result)
            {
                return View("/Home/Error");
            }

            ViewBag.Type = type;
            ViewBag.ParentId = parentId;
            return View();
        }

        public async Task<ResultList> List(BasicTypeQueryDTO dto)
        {
            var result = await _service.GetPageList(dto);
            var map = _mapper.Map<List<BasicTypeListDTO>>(result.Item1);
            return ResultList.Success(count: result.Item2, data: map);
        }

        public async Task<Result> Del(string id)
        {
            return await _service.Delete(id, OperatorInfo) ? Result.Success("删除成功") : Result.Failed(-1, "删除失败");
        }

        public async Task<Result> Delist(List<string> ids)
        {
            return await _service.DeleteBatch(ids, OperatorInfo) ? Result.Success("删除成功") : Result.Failed(-1, "删除失败");
        }

        public async Task<IActionResult> Edit(string type, string parentId, string id)
        {
            var pageUrl = $"/Basic/BasicType/Edit?type={type}";
            var result = _userRole.Check(UserInfo, pageUrl);
            if (!result)
            {
                return View("/Home/Error");
            }

            if (string.IsNullOrWhiteSpace(id))
            {
                var initModel = new BasicTypeDetailDTO();
                initModel.Type = type;
                initModel.ParentId = parentId;
                return View(initModel);
            }
            else
            {
                var model = await _service.GetById(id);
                var modelDTO = _mapper.Map<BasicTypeDetailDTO>(model);
                return View(modelDTO);
            }
        }

        public async Task<Result> Save(BasicTypeDetailDTO dto)
        {
            dto.PicUrl = string.Empty;
            return await _service.Save(dto, OperatorInfo);
        }

        [NoLogin]
        public async Task<Result> GetList(BasicTypeQueryDTO dto)
        {
            var result = await _service.GetList(dto);
            return Result.Success(data: result);
        }
    }
}